package mh.log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * This class handle the setup of the Logger, create the main logger and set up <code>FileHandler</code> and
 * <code>ConsoleHandler</code>
 * 
 * @author Gianmarco Laggia
 * 
 */
public class MHLogger {

	/**
	 * Create and set up the logger and its handlers.<br>
	 * This class set up also system's properties.
	 * 
	 * @throws IOException
	 *             In case the properties file not exist
	 */
	public static void setup() throws IOException {

		Logger logger = Logger.getLogger("");
		InputStream propFile = logger.getClass().getResourceAsStream("/MH.properties");
		Properties p = new Properties(System.getProperties());
		p.load(propFile);
		// set the system properties
		System.setProperties(p);

		LogManager.getLogManager().readConfiguration(propFile);
		logger.setLevel(Level.FINEST);

		DateFormat dateFormat = new SimpleDateFormat("dd MM yyyy");
		DateFormat hourFormat = new SimpleDateFormat("HH-mm");

		String folder = dateFormat.format(new Date());
		new File("log/" + folder).mkdirs();

		FileHandler fileHTML = new FileHandler("log/" + folder + "/log_" + hourFormat.format(new Date()) + ".html");
		MHFormatter formatterHTML = new MHFormatter();
		fileHTML.setFormatter(formatterHTML);
		logger.addHandler(fileHTML);

		// Create txt Formatter
		MHConsoleHandler ch = new MHConsoleHandler();
		SimpleFormatter formatter = new SimpleFormatter();
		ch.setFormatter(formatter);
		logger.addHandler(ch);
		ch.setLevel(Level.CONFIG);

		logger = Logger.getLogger("Exception");
		LogOutputStream los = new LogOutputStream(logger, Level.SEVERE);
		System.setErr(new PrintStream(los, true));
		//		PrintStream out = new PrintStream(new LogOutputStream(), true);
		//		System.setOut(out);

	}
}
